package com.test.thread.example05;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore 控制任务提交速度
 */
public class Example01 {

    public static void main(String[] args) throws InterruptedException {
        // 创建一个包含两个线程的线程池，使用 CallerRunsPolicy 来处理被拒绝的任务
        ExecutorService executorService = new ThreadPoolExecutor(
            2, // 核心线程数
            2, // 最大线程数
            0L, // 空闲线程超时时间
            TimeUnit.MILLISECONDS, // 时间单位
            new LinkedBlockingQueue<>(2), // 任务队列
            Executors.defaultThreadFactory(), // 线程工厂
            new ThreadPoolExecutor.CallerRunsPolicy() // 任务被拒绝时的处理策略
        );

        final SemaphoreUsage semaphoreUsage = new SemaphoreUsage(executorService, 5);

        // 提交任务
        for (int i = 1; i <= 100; i++) {
            final int taskId = i;
            semaphoreUsage.submitTask(() -> {
                System.out.println("执行任务 " + taskId + "，线程：" + Thread.currentThread().getName());
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }

        executorService.shutdown();

    }
}
